namespace CRM_Perf_BenchMark
{
	using System;
	using System.Collections.Generic;
	using Microsoft.VisualStudio.TestTools.WebTesting;
	using System.Net;
	using System.Text;
	using System.Xml;
	
    /// <summary>
    /// 1. Start at Sales tab
    /// 2. Click on Leads
    /// 3. Click New button
    /// 4. Add relevant data (subject, firstname, lastname, company)
    /// 5. Click Save&Close
    /// </summary>

	public class CreateNewLead : CrmWebTest
	{
		public void	CreateNewLead_PreWebTest(object	sender,	PreWebTestEventArgs	e)
		{
            EntityRequest er = new EntityRequest();
            er.Type = EntityNames.Users;
            er.ReturnAs = EntityNames.Users;
            er.ParentID = EntityManager.Instance.OrgId;

            System.Collections.Hashtable userProps = new System.Collections.Hashtable();
            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                userProps.Add("role", e.WebTest.Context["UserRole"]);
                er.Props = userProps;
            }

            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

            user = (CRMEntity)Entities[EntityNames.Users];

            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);
            orgId = new Guid(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];            
		}

		public void	CreateNewLead_PostWebTest(object sender, PostWebTestEventArgs e)
		{
			try
			{
                if (newLeadId != null)
                {
                    newLeadId = new Guid(newLeadId).ToString();
                    Guid g = EntityManager.Instance.GetOwnerGuid(new Guid(user[EntityIDNames.User]), new Guid(user["OrganizationId"]));
                    EntityManager.Instance.AddEntity(EntityNames.Leads, g, new string[] { "OwningUser", "LeadID", "FirstName", "LastName", "EntityManagerOwningUser" }, new string[] { user["systemuserid"], newLeadId, firstname, lastname , g.ToString()});
                }
			}
            catch (System.FormatException fe)
            {
                System.Diagnostics.Trace.WriteLine("Failed to convert bogus data into Guid. " + fe.ToString());
            }
			finally
			{
				EntityManager.Instance.FreeEntity(user);
			}
		}

		private void NewLead_ValidateResponse(object sender, ValidationEventArgs e)
		{
			string ID = null;

			int idIdx = e.Response.BodyString.IndexOf(newIdMarker);
			ID = e.Response.BodyString.Substring(idIdx + (CreateNewLead.newIdMarker.Length), 36);
			try
			{
				ID = new Guid(ID).ToString();
			}
			catch (System.FormatException fe)
			{
				System.Diagnostics.Trace.WriteLine("Format exception: " + fe.ToString());
				e.IsValid = false;
				return;
			}
			e.IsValid = true;
		}

		public CreateNewLead()
		{
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            gridXml = GridXmlHelper.LeadPageViewRefresh(-1, myOpenLeadsView, null);

			this.Proxy = null;            
			PreWebTest += new EventHandler<PreWebTestEventArgs>(CreateNewLead_PreWebTest);
			PostWebTest	+= new EventHandler<PostWebTestEventArgs>(CreateNewLead_PostWebTest);
		}

		public override	IEnumerator<WebTestRequest>	GetRequestEnumerator()
		{
			this.BeginTransaction("NavLeadHomepage");

            _root_homepage_aspx hp = new _root_homepage_aspx(user);
			hp.etc = 4;
			yield return (hp);
                        
			this.EndTransaction("NavLeadHomepage");
			
			this.BeginTransaction("CreateLead");

            sfa_leads_edit_aspx dp = new sfa_leads_edit_aspx(user);
			yield return (dp);

            referer = dp.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx formScript = new _forms_FormScript_js_aspx(user);
            formScript.etc = 4;
            formScript.FormType = "main";
            formScript.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            formScript.Headers.Add(headerItem);
            yield return (formScript);
            			
			// if the Help and Assistance Pane is on	and	the	user tabs through the fields of	the	Lead
			// detail pane,	they'll	hit	this (heavy) request when the tab into the 
			// primay Lead field.
			if (ConfigSettings.Default.HelpAndAssistancePaneOn	== "true")
			{
				//TODO:	implement for Lead.	 See CreateNewAccount for reference.
			}

            dp = new sfa_leads_edit_aspx(user);
            lastname = Utils.GetRandomString(5, 10);
            firstname = Utils.GetRandomString(5, 10);

            dp.crmFormSubmitXml = EntityXmlHelper.GetCreateLeadXml(new Guid(user[EntityIDNames.User]), 8, firstname, lastname);
			dp.crmFormSubmitMode = 1;
            dp.crmFormUserModified = true;
			dp.crmFormSubmitObjectType = 4;
			dp.crmFormSubmitSecurity = 852023;
			dp.crmFormSubmitOnline = 1;
            rpcInfo = Utils.GenerateWRPCToken(sfa_leads_edit_aspx.url, user, tokenKey);
            dp.CRMWRPCToken = rpcInfo.token;
            dp.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
			dp.ValidateResponse += this.NewLead_ValidateResponse;
			yield return (dp);

			//get the newly	created	Lead id	out	of the post	reply
			int	idIdx =	dp.lastResponse.BodyString.IndexOf(newIdMarker);
			string tempNewLeadId =	dp.lastResponse.BodyString.Substring(idIdx + (CreateNewLead.newIdMarker.Length), 36);
			newLeadId = new Guid(tempNewLeadId).ToString();

			AppGridWebService.AppGridWebService	agws = new AppGridWebService.AppGridWebService();

			WebTestRequest wtrRefresh =	null;
            try { agws.Refresh(gridXml); }
			catch (crmException	x)
			{
				wtrRefresh = x.wtr;
                wtrRefresh.Url = Utils.ReplaceServerName(wtrRefresh.Url, user);

                string urlPath = wtrRefresh.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtrRefresh.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtrRefresh.Headers.Add(headerItem);
                wtrRefresh.Method = "Post";
			}
			yield return (wtrRefresh);

			this.EndTransaction("CreateLead");
		}

        private const string newIdMarker = @"separator + ""id=";
		private	CRMEntity user;
		private	string newLeadId;        
        private string gridXml;
        private string crmServer;
        private string tokenKey;
        private static string myOpenLeadsView = "00000000-0000-0000-00AA-000010001005";

        private Guid orgId;
        private string firstname;
        private string lastname;
        private string referer;
        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
	}
}